home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / python-support / python-rdflib / rdflib / syntax / serializer.py < prev    next >
Encoding:
Python Source  |  2007-04-04  |  1.7 KB  |  52 lines

  1. import tempfile, shutil, os
  2. from threading import Lock
  3. from urlparse import urlparse
  4.  
  5. try:
  6.     from cStringIO import StringIO
  7. except ImportError:
  8.     from StringIO import StringIO
  9.  
  10.  
  11. class Serializer(object):
  12.  
  13.     def __init__(self, serializer):
  14.         self.serializer = serializer
  15.         self.__save_lock = Lock()
  16.  
  17.     def _get_store(self):
  18.         return self.serializer.store
  19.  
  20.     def _set_store(self, store):
  21.         self.serializer.store = store
  22.  
  23.     store = property(_get_store, _set_store)
  24.  
  25.     def serialize(self, destination=None, format="xml", base=None, encoding=None, **args):
  26.         if destination is None:
  27.             stream = StringIO()
  28.             self.serializer.serialize(stream, base=base, encoding=encoding)
  29.             return stream.getvalue()
  30.         if hasattr(destination, "write"):
  31.             stream = destination
  32.             self.serializer.serialize(stream, base=base, encoding=encoding)
  33.         else:
  34.             location = destination
  35.             try:
  36.                 self.__save_lock.acquire()
  37.                 scheme, netloc, path, params, query, fragment = urlparse(location)
  38.                 if netloc!="":
  39.                     print "WARNING: not saving as location is not a local file reference"
  40.                     return
  41.                 name = tempfile.mktemp()
  42.                 stream = open(name, 'wb')
  43.                 self.serializer.serialize(stream, base=base, encoding=encoding, **args)
  44.                 stream.close()
  45.                 if hasattr(shutil,"move"):
  46.                     shutil.move(name, path)
  47.                 else:
  48.                     shutil.copy(name, path)
  49.                     os.remove(name)
  50.             finally:
  51.                 self.__save_lock.release()
  52.